package com.example.smart.order.controller;

import com.example.smart.order.entity.DiningTable;
import com.example.smart.order.entity.OrderInfo;
import com.example.smart.order.mapper.DiningTableMapper;
import com.example.smart.order.mapper.OrderInfoMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@Slf4j
@RequestMapping("/api/diningTables")
public class DiningTableController {
    @Autowired
    private DiningTableMapper diningTableMapper;
    @Autowired
    private OrderInfoMapper orderInfoMapper; // 自动装配OrderInfoMapper接口对象

    /**
     * 获取所有餐桌列表
     *
     * @return 餐桌列表
     */
    @RequestMapping("")
    public List<DiningTable> getDiningTables() {
        log.debug("获取餐桌列表");
        // 调用Mapper接口查询所有餐桌
        List<DiningTable> tables = diningTableMapper.selectAll();
        log.debug("查询到餐桌列表: {}", tables);
        return tables;
    }

    /**
     * 增加餐桌
     *
     * @param diningTable 餐桌对象
     * @return 影响的行数
     */
    @PostMapping("/addNew")
    public int addNew(DiningTable diningTable) {
        log.debug("增加餐桌: {}", diningTable);
        diningTable.setQrCodePath("");
        int result = diningTableMapper.insert(diningTable);
        log.debug("增加餐桌结果: {}", result);
        return result;
    }

    /**
     * 根据ID删除餐桌
     *
     * @param tableId 餐桌ID
     * @return 影响的行数，如果存在未结账订单则返回-1
     */
    @PostMapping("/delete")
    public int delete(Long tableId) {
        log.debug("删除餐桌, ID: {}", tableId);
        List<OrderInfo> unpaidOrders = orderInfoMapper.selectByTableIdAndNotPaid(tableId); // 查询未结账订单
        if (unpaidOrders.size() > 0) {
            log.debug("存在未结账订单，删除操作被阻止");
            return -1; // 如果存在未结账订单，返回-1
        }
        int result = diningTableMapper.deleteById(tableId); // 删除餐桌
        log.debug("删除餐桌结果: {}", result);
        return result;
    }
}